﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;

using Lucene.Net.QueryParsers;
using Lucene.Net.Analysis.Standard;

using CloudSoft.Workflows;
using ERPStore.Indexers.Lucene.Models;
using ERPStore.Extensions;

using CloudSoft.Extensions;

namespace ERPStore.Indexers.Lucene.Workflows.Activities
{

	public sealed class ReloadProduct : CodeActivity
	{
		public InArgument<ERPStore.Models.Product> Product { get; set; }
		public InArgument<global::Lucene.Net.Util.Version> LuceneVersion { get; set; }

		protected override void Execute(CodeActivityContext context)
		{
			var product = context.GetValue(this.Product);
			var luceneVersion = context.GetValue(this.LuceneVersion);
			
			var repository = context.GetService<Repositories.LuceneRepository>();
			var logger = context.GetService<Logging.ILogger>();
			var builder = context.GetService<Services.IndexBuilder>();
			var validatorService = context.GetService<ERPStore.Services.IValidatorService>();

			var brokenRules = validatorService.Validate(product);
			if (brokenRules.IsNotNullOrEmpty())
			{
				logger.Warn("Invalid product : {0}", brokenRules.ToFullReason());
				return;
			}

			var worker = builder.GetCurrentWorker();
			if (worker != null
				&& !worker.TerminatedDate.HasValue)
			{
				// No modification while another index is building
				logger.Warn("Modification denied when another index is building");
				return;
			}

			var query = string.Format("Id:{0}", product.Id);
			var parser = new QueryParser(luceneVersion, "Id", new StandardAnalyzer(luceneVersion));
			var q = parser.Parse(query);

			// Deleting document before
			repository.DeleteDocument(q);

			// Converting to document 
			var doc = product.ToDocument();

			// Append document
			repository.AddDocument(doc);
			logger.Info("Append product {0} {1} to lucene live index", product.Code, product.Title);
		}
	}
}
